package com.skywolf.chem.common.sysconfig.utils;

/**
 * Created by pei_pei on 2020/10/27.
 */

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public final class PasswordGenerator {
    private static final String AlphaNumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvxyz";
    private static final int SALTLENGTH = 8;
    public static final String DEFAULT_PASSWORD = "123456";

    public PasswordGenerator() {
    }

    public static String genSalt() {
        SecureRandom random = null;

        try {
            random = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException var4) {
            var4.printStackTrace();
        }

        char[] token = new char[8];

        for(int i = 0; i < 8; ++i) {
            int index = random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvxyz".length());
            token[i] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvxyz".charAt(index);
        }

        return new String(token);
    }

    public static String genPassword(String rawPassword, String salt) {
        String finalPassword = null;

        try {
            MessageDigest e = MessageDigest.getInstance("SHA-256");
            e.update(salt.getBytes());
            byte[] result = e.digest(rawPassword.getBytes());
            StringBuilder sb = new StringBuilder();

            for(int i = 0; i < result.length; ++i) {
                sb.append(Integer.toString((result[i] & 255) + 256, 16).substring(1));
            }

            finalPassword = sb.toString();
        } catch (NoSuchAlgorithmException var7) {
            var7.printStackTrace();
        }

        return finalPassword;
    }

    public static PasswordGenerator.Passwords genPassword(String rawPassword) {
        String salt = genSalt();
        String password = genPassword(rawPassword, salt);
        return new PasswordGenerator.Passwords(salt, password);
    }

    public static PasswordGenerator.Passwords genDefaultPassword() {
        String salt = genSalt();
        String password = genPassword("123456", salt);
        return new PasswordGenerator.Passwords(salt, password);
    }

    public static boolean vatify(String rawPassword, String encodingPassword, String salt) {
        return encodingPassword.equals(genPassword(rawPassword, salt));
    }

    public static class Passwords {
        private String salt;
        private String password;

        public Passwords(String salt, String password) {
            this.salt = salt;
            this.password = password;
        }

        public String getSalt() {
            return this.salt;
        }

        public String getPassword() {
            return this.password;
        }
    }
}

